package research;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import db.beans.M_CategoryBean;

public class CategoryMap {

	
    public static HashMap<Long, CategoryTree> getCategoryMap(M_CategoryBean[] categoryRec) {
    	HashMap<Long, CategoryTree> categoryMap = null;
    	if (categoryRec != null && categoryRec.length > 0){
    		categoryMap = new HashMap<Long, CategoryTree>();
    		for (M_CategoryBean rec : categoryRec){
				CategoryTree categoryTree = new CategoryTree();
				categoryTree.setCategory(rec);
    			categoryMap.put(new Long(rec.getCategoryCode()), categoryTree);
    		}
    		
    		initCategoryTree(categoryMap);
    	}
    	return categoryMap;
    }
    
    private static void initCategoryTree(HashMap<Long, CategoryTree> categoryMap){
    	
        Iterator<Long> it = categoryMap.keySet().iterator();
        Long key;
        CategoryTree categoryTreeParent;
        CategoryTree categoryTree;
        M_CategoryBean rec;
        Long belongCode;
        while (it.hasNext()) {
            key = it.next();
            categoryTree = categoryMap.get(key);
            rec = categoryTree.getCategory();
            belongCode = new Long(rec.getBelongCategoryCode());
            if (rec != null){
            	if (rec.getBelongCategoryCode() == -1){
            		categoryTree.setParent(null);
            	} else {
            		categoryTreeParent = categoryMap.get(belongCode);
            		categoryTreeParent.addChild(categoryTree);
            		categoryTree.setParent(categoryTreeParent);
            		categoryTree.setParentCategoryCode(belongCode);
            	}
            }
        }
    }
    
    public static M_CategoryBean[] getCategoryByCategoryCode(HashMap<Long, CategoryTree> categoryMap, long categoryCode){
    	Vector<M_CategoryBean> v = new Vector<M_CategoryBean>();
    	CategoryTree categoryTree = categoryMap.get(new Long(categoryCode));
    	List<CategoryTree> childList = categoryTree.getChild();
    	
    	if (childList == null || childList.size() == 0){
    		v.add(categoryTree.getCategory());
    	} else {
    		setCategory(childList, v);
    	}
    	
    	return (M_CategoryBean[])v.toArray(new M_CategoryBean[v.size()]);
    }
    
    private static void setCategory(List<CategoryTree> list, Vector<M_CategoryBean> v){
    	CategoryTree categoryTree;
    	for (int i = 0; i < list.size(); i++){
    		categoryTree = list.get(i);
        	List<CategoryTree> childList = categoryTree.getChild();
        	if (list == null || list.size() == 0){
        		v.add(categoryTree.getCategory());
        	} else {
        		setCategory(childList, v);
        	}
    	}
    }
}
